/** 
 * File-Name:ArticleRepository.java
 *
 * Created on 2011-6-2 下午03:48:12
 * 
 * @author: Neo (neolimeng@gmail.com)
 * Software Engineering Institute, Peking University, China
 * 
 * Copyright (c) 2009, Peking University
 * 
 *
 */
package xiaoyou.service;

import java.sql.Connection;
import java.util.Date;
import java.util.List;

import org.apache.commons.dbutils.DbUtils;
import org.apache.log4j.Logger;

import xiaoyou.dao.ArticleDao;
import xiaoyou.entity.Article;
import xiaoyou.neoutil.CommonService;
import xiaoyou.neoutil.DaoSupport;
import xiaoyou.neoutil.Page;

/**
 * Description: 用户Article的各种存储相关操作。
 * 
 * @author: Neo (neolimeng@gmail.com) Software Engineering Institute, Peking
 *          University, China
 * @version 1.0 2011-6-2 下午03:48:12
 */
public class ArticleRepository extends CommonService {
	private static Logger log = Logger.getLogger(ArticleRepository.class);
	private String SQL_INSERT = "INSERT INTO article(uuid, title, content, imagePath, filePath, authorId, type, publishDate, updateDate, entityStatus, reserve01, reserve02, reserve03, reserve04, reserve05) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
	private String SQL_UPDATE = "UPDATE article SET uuid=?, title=?, content=?, imagePath=?, filePath=?, authorId=?, type=?, updateDate=?, entityStatus=?, reserve01=?, reserve02=?, reserve03=?, reserve04=?, reserve05=? WHERE id=?";
	private String SQL_GET_BY_ID = "SELECT * FROM article WHERE id=? and entityStatus=1";
	private String SQL_GET_BY_UUID = "SELECT * FROM article WHERE uuid=? AND entityStatus=1";
	private String SQL_GET_LATEST_ONE_BY_TYPE = "SELECT * FROM article WHERE type=? AND entityStatus=1 ORDER BY updateDate DESC";
	private String SQL_GET_BY_TYPE = "SELECT * FROM article WHERE type=? AND entityStatus=1 ORDER BY updateDate DESC";
	private String SQL_GET_LATEST_BY_TYPE = "SELECT * FROM article WHERE type=? AND entityStatus=1 ORDER BY updateDate DESC LIMIT 0,?";
	private String SQL_DELETE_BY_ID = "UPDATE article SET entityStatus=0 WHERE id=?";
	private String SQL_SEARCH_BY_KEYWORD = "SELECT * FROM article WHERE entityStatus=1 and title like %?%";

	public int save(Article article) {
		Connection connection = DaoSupport.getConnection();
		ArticleDao articleDao = new ArticleDao(connection);

		try {
			Object[] params = { article.getUuid(), article.getTitle(),
					article.getContent(), article.getImagePath(),
					article.getFilePath(), article.getAuthorId(),
					article.getType(), new Date(), new Date(),
					article.getEntityStatus(), article.getReserve01(),
					article.getReserve02(), article.getReserve03(),
					article.getReserve04(), article.getReserve05() };
			articleDao.execute(SQL_INSERT, params);
			return SUCCESS;
		} catch (Exception e) {
			log.error("保存Article对象出现异常！！");
			e.printStackTrace();
			return FAIL;
		} finally {
			try {
				DbUtils.close(connection);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	public int update(Article article) {
		Connection connection = DaoSupport.getConnection();
		ArticleDao articleDao = new ArticleDao(connection);

		try {
			Object[] params = { article.getUuid(), article.getTitle(),
					article.getContent(), article.getImagePath(),
					article.getFilePath(), article.getAuthorId(),
					article.getType(), new Date(), article.getEntityStatus(),
					article.getReserve01(), article.getReserve02(),
					article.getReserve03(), article.getReserve04(),
					article.getReserve05(), article.getId() };
			articleDao.execute(SQL_UPDATE, params);
			return SUCCESS;
		} catch (Exception e) {
			log.error("更新Article对象出现异常！！");
			e.printStackTrace();
			return FAIL;
		} finally {
			try {
				DbUtils.close(connection);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	public int delete(long id) {
		Connection connection = DaoSupport.getConnection();
		ArticleDao articleDao = new ArticleDao(connection);

		try {
			Object[] params = { id };
			articleDao.execute(SQL_DELETE_BY_ID, params);
			return SUCCESS;
		} catch (Exception e) {
			log.error("假删除Article对象出现异常！！");
			e.printStackTrace();
			return FAIL;
		} finally {
			try {
				DbUtils.close(connection);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	public Article get(long id) {
		Connection connection = DaoSupport.getConnection();
		ArticleDao articleDao = new ArticleDao(connection);

		try {
			Object[] params = { id };
			List<Article> articles = articleDao.find(SQL_GET_BY_ID, params);
			if (articles == null || articles.size() == 0) {
				return null;
			} else if (articles.size() > 1) {
				log.error("根据ID查询到的Article个数不唯一，为防止错误，返回null!");
				return null;
			} else {
				return articles.get(0);
			}
		} catch (Exception e) {
			log.error("根据ID取得Article对象出现异常！！");
			e.printStackTrace();
			return null;
		} finally {
			try {
				DbUtils.close(connection);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	public Article get(String uuid) {
		Connection connection = DaoSupport.getConnection();
		ArticleDao articleDao = new ArticleDao(connection);

		try {
			Object[] params = { uuid };
			List<Article> articles = articleDao.find(SQL_GET_BY_UUID, params);
			if (articles == null) {
				return null;
			} else if (articles.size() > 1) {
				log.error("根据UUID查询到的Article个数不唯一，为防止错误，返回null!");
				return null;
			} else {
				Article article = articles.get(0);

				UserRepository userRepository = new UserRepository();
				article.setAuthor(userRepository.get(article.getAuthorId()));

				return article;
			}
		} catch (Exception e) {
			log.error("根据UUID取得Article对象出现异常！！");
			e.printStackTrace();
			return null;
		} finally {
			try {
				DbUtils.close(connection);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	public Page<Article> getArticlesByType(final Page<Article> page, int type) {
		Connection connection = DaoSupport.getConnection();
		ArticleDao articleDao = new ArticleDao(connection);

		try {
			Object[] params = { type };
			Page<Article> articles = articleDao.find(page, SQL_GET_BY_TYPE,
					params);
			articles.setTotalCount(articleDao.count(SQL_GET_BY_TYPE, params));
			return articles;
		} catch (Exception e) {
			log.error("根据Type取得Article对象出现异常！！");
			e.printStackTrace();
			return null;
		} finally {
			try {
				DbUtils.close(connection);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	public Article getTheLatestByType(int type) {
		Connection connection = DaoSupport.getConnection();
		ArticleDao articleDao = new ArticleDao(connection);

		try {
			Object[] params = { type };
			List<Article> articles = articleDao.find(
					SQL_GET_LATEST_ONE_BY_TYPE, params);
			if (articles == null || articles.size() == 0) {
				return null;
			} else {
				log.info("根据ID查询到的Article个数不唯一，选取第一个!");
				Article article = articles.get(0);

				UserRepository userRepository = new UserRepository();
				article.setAuthor(userRepository.get(article.getAuthorId()));

				return article;
			}
		} catch (Exception e) {
			log.error("按类别取得最新的Article，取得Article对象出现异常！！");
			e.printStackTrace();
			return null;
		} finally {
			try {
				DbUtils.close(connection);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	public Page<Article> search(Page<Article> page, String query) {
		Connection connection = DaoSupport.getConnection();
		ArticleDao articleDao = new ArticleDao(connection);

		try {
			Page<Article> articles = articleDao.find(page,
					"SELECT * FROM article WHERE entityStatus=1 and title like '%"
							+ query + "%'");
			
			articles.setTotalCount(articleDao.count("SELECT * FROM article WHERE entityStatus=1 and title like '%"+ query + "%'"));
			return articles;
		} catch (Exception e) {
			log.error("搜索Article对象出现异常！！");
			e.printStackTrace();
			return null;
		} finally {
			try {
				DbUtils.close(connection);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	public List<Article> getLatestArticlesByType(int type, int topNum) {
		Connection connection = DaoSupport.getConnection();
		ArticleDao articleDao = new ArticleDao(connection);

		try {
			Object[] params = { type, topNum };
			List<Article> articles = articleDao.find(SQL_GET_LATEST_BY_TYPE,
					params);
			return articles;
		} catch (Exception e) {
			log.error("根据Type取得Article对象出现异常！！");
			e.printStackTrace();
			return null;
		} finally {
			try {
				DbUtils.close(connection);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	/**
	 * Description:
	 * 
	 * @param args
	 *            void
	 */
	public static void main(String[] args) {
		Article article = new Article();
		article.setTitle("北科大校友基金会最新通知");
		article.setContent("北京科技大学校友基金会最新通知内容如下。");
		article.setAuthorId(1L);
		article.setType(Article.NOTICE);

		ArticleRepository articleRepository = new ArticleRepository();
		// articleRepository.update(article);
		articleRepository.save(article);

		List<Article> articles = articleRepository.getLatestArticlesByType(
				Article.NOTICE, 3);
		System.out.println(articles.size());

	}

}
